import { $helper, $http, $page, } from "@/utils";
import { useStorage } from "@/utils/storage";
import { $SCAN_ACTION } from "@/utils/const/env";

/**
 * 节流函数会确保在指定的时间间隔内，函数被调用的次数不超过设定的阈值。
 * @param func 节流函数
 * @param wait 时间（毫秒）
 * @returns function
 */
export function throttle<F extends (...args: any[]) => void>(func: F, wait: number): F {
    let timer: ReturnType<typeof setTimeout> | undefined;
    return function (this: ThisParameterType<F>, ...args: Parameters<F>) {
        if (!timer) {
            func.apply(this, args);
            timer = setTimeout(() => {
                timer = undefined;
            }, wait);
        }
    } as F;
}
/**
 * 防抖函数会延迟函数的执行，直到一定的静默期过去后，才真正执行该函数。
 * @param func 防抖函数
 * @param wait 时间（毫秒）
 * @returns function
 */
export function debounce<F extends (...args: any[]) => void>(func: F, wait: number): F {
    let timer: ReturnType<typeof setTimeout> | undefined;
    return function (this: ThisParameterType<F>, ...args: Parameters<F>) {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = undefined;
            func.apply(this, args);
        }, wait);
    } as F;
}

export function formatDate(timestamp: number, formatType: string) {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);

    let formattedDate = '';

    switch (formatType) {
        case 'YYYY年MM月DD日':
            formattedDate = `${year}年${month}月${day}日`;
            break;
        case 'MM/DD/YYYY':
            formattedDate = `${month}/${day}/${year}`;
            break;
        default:
            formattedDate = `${year}-${month}-${day}`;
    }

    return formattedDate;
}
export function getDayName(d: Date) {
    const now = d.getTime();
    const start = new Date();
    start.setHours(0, 0, 0, 0);
    const end = new Date();
    end.setHours(23, 59, 59, 999);
    switch (true) {
        case now >= start.getTime() && now <= end.getTime():
            return '今天';
        case now >= start.getTime() + 86400000 && now <= end.getTime() + 86400000:
            return '明天';
        case now >= start.getTime() + 172800000 && now <= end.getTime() + 172800000:
            return '后天';
        default:
            return (d.getMonth() + 1) + '月' + d.getDate() + '日';
    }
}
export function getTimeText(t: number) {
    let text = '';
    let h = 0, hText = '';
    if (t > 3600) {
        h = Math.floor(t / 3600);
        hText = `${h}小时`;
        t = t % 3600
    }
    const m = Math.floor(t / 60).toString().padStart(2, '0');
    const s = Math.ceil(t % 60).toString().padStart(2, '0');
    text = `${hText}${m}分${s}秒`
    return text;
}
/**
 * 数字千分位格式化并保留小数点后两位
 * @param num 数字
 * @param precision 小数点后位数
 * @returns string
 */
export function formatNumber(num: number, precision = 0): string {
    if (!num || isNaN(num)) {
        return '0';
    }
    const arr = String(num).split('.');
    const int = arr[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    if (precision === 0) {
        return int;
    }
    // 判断是否有小数，有则四舍五入保留两位小数
    if (arr.length === 2) {
        return `${int}.${arr[1].slice(0, precision)}`;
    } else {
        return `${int}.00`;
    }
}
export function makePhoneCall(phone: string) {
    if (!phone) {
        return;
    }
    uni.makePhoneCall({
        phoneNumber: phone,
    });
}
export function setClipboard(data: string) {
    uni.setClipboardData({
        data
    });
}
export function isURL(url: string) {
    return /^(http|https):\/\/[^ "]+$/.test(url);
}
export function scanCode(options?:UniNamespace.ScanCodeOptions) {
        $helper.scanCode({
            success: (res: any) => {
                console.log();
                // "result": "https://saas.kf.renloong.com/app/ycMassage/#/technician/pages/index/verification?appid=2&code=ci1ZlRi6foisC762NKZEQU45M3RYenlmQTUyQ1J2U2FjeTI3Ync9PQ%3D%3D",
                const result = decodeURIComponent(res.result);
                if (result.startsWith($http.baseHOST)) {
                    const [url, hash] = result.split('#');
                    const [action, queryStr] = hash.split('?');
                    const query = queryStr.split('&').reduce((obj: any, item: string) => {
                        const [key, value] = item.split('=');
                        obj[key] = value;
                        return obj;
                    }, {});
                    switch (action) {
                        case $SCAN_ACTION.TECHNICIAN_VERIFICATION:
                            console.log(hash);
                            $page.open({
                                url:hash
                            })
                            break;
                        default:
                            useStorage().set('ScanResult', result).then(() => {
                                $page.open('/pages/scan/result?view=webview')
                            })
                            break;
                    }
                // #ifdef APP
                } else if (isURL(result)) {
                    uni.showModal({
                        title: '是否在浏览器打开链接？',
                        content: result,
                        success: (res) => {
                            if (res.confirm) {
                                plus.runtime.openURL(result);
                            }
                        }
                    });
                // #endif
                } else {
                    useStorage().set('ScanResult', result).then(() => {
                        $page.open('/pages/scan/result')
                    })
                }
            },
            ...options
        })
}
export const formatFriendlyTime=(input: string | number)=>{
    let date: Date;
    if (typeof input === 'string') {
        date = new Date(input.replace(/-/g, '/'));
    } else if (typeof input === 'number') {
        date = new Date(input);
    } else {
        throw new Error('Invalid input type. Expected a string or a number.');
    }

    const now:Date = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);

    if (diffInSeconds < 10) {
        return "刚刚";
    } else if (diffInSeconds < 60) {
        return `${diffInSeconds}秒前`;
    } else if (diffInSeconds < 3600) {
        return `${Math.floor(diffInSeconds / 60)}分钟前`;
    } else if (diffInSeconds < 86400) {
        return `${Math.floor(diffInSeconds / 3600)}小时前`;
    } else {
        const yesterday = new Date(now);
        yesterday.setDate(now.getDate() - 1);
        if (date.getFullYear() === yesterday.getFullYear() &&
            date.getMonth() === yesterday.getMonth() &&
            date.getDate() === yesterday.getDate()) {
            return "昨天";
        }

        const thisMonth = new Date(now.getFullYear(), now.getMonth(), 1);
        if (date >= thisMonth) {
            return `${Math.floor(diffInSeconds / 86400)}天前`;
        }

        const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        if (date >= lastMonth && date < thisMonth) {
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${month}月-${day}日`;
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}年-${month}月-${day}日`;
    }
}